import { Controller } from 'egg';
import { Result } from '../util/result';
import MsgEnum from '../util/msgEnum';
import fileReader from '../util/readFile';
import * as jwt from 'jsonwebtoken';
import { v4 as uuidv4 } from "uuid";

export default class HomeController extends Controller {
  public async index() {
    const { ctx } = this;

    ctx.body = await ctx.service.test.sayHi('egg');
  }

  private async createToken(params) {
    return `Bearer ${jwt.sign(params, process.env.TOKEN_SECRET as jwt.Secret, {
      expiresIn: 36000,
    })}`;
  }

  public async userLogin() {
    const { ctx, app } = this;
    const errors = app.validator.validate(
      {
        account: { type: 'string', require: true, allowEmpty: false },
        password: { type: 'password', require: true, allowEmpty: false },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 401;
      ctx.body = new Result(errors, MsgEnum.LOGIN_PARAM_FAIL);
    } else {
      const { account, password } = ctx.request.body;
      const user = await this.ctx.service.user.findUser(account, password);
      if (user) {
        const { id, name, state, identity } = user;
        console.log(identity);
        const params = {
          id,
          name,
        };
        // jwt生成token
        const token = await this.createToken(params);
        ctx.body = new Result(
          {
            token,
            id,
            name,
            state,
            identity,
          },
          MsgEnum.LOGIN_SUCCESS
        );
      } else {
        ctx.status = 400;
        ctx.body = new Result(undefined, MsgEnum.LOGIN_FAIL);
      }
    }
  }
  public async getSelections() {
    const {ctx} = this;

    const areas = await ctx.model.ApplicationArea.findAll({
      attributes: ["id", "uuid", "name"],
    });

    const orgType = await ctx.model.OrganizationType.findAll({
      attributes: ["id", "uuid", "name"],
    });

    const talentType = await ctx.model.TalentClassfication.findAll({
      attributes: ["id", "uuid", "typeName"],
    });

    // 职称
    const titleType = await ctx.model.Title.findAll({
      attributes: ["id", "uuid", "name"],
    });

    // 职务
    const positionType = await ctx.model.Position.findAll({
      attributes: ["id", "uuid", "name"],
    });

    const education = [
      "小学",
      "初中",
      "高中",
      "中专",
      "大专",
      "本科",
      "硕士",
      "博士",
    ];

    const patentType = ["发明", "实用新型", "外观设计"];

    // TODO: add other selections
    ctx.body = new Result({
      applicationArea: areas,
      organizationType: orgType,
      talentType,
      education,
      titleType,
      positionType,
      patentType,
    });
  }

  public async downloadTemplate() {
    const { ctx, app } = this;
    const errors = app.validator.validate(
      {
        filename: { require, type: 'string', convertType: 'string' },
        dir: { require, type: 'string', convertType: 'string' },
      },
      ctx.request.body
    );
    if (errors) {
      ctx.status = 400;
      ctx.body = new Result(null, MsgEnum.PARAMETER_VERIFICATION_ERROR);
    } else {
      const { filename, dir } = ctx.request.body;
      const result = await fileReader(filename, dir);
      const res = new Result(result);
      if (res.mainData == null) {
        ctx.status = 406;
      }
      ctx.body = res;
    }
  }

  public async getOrganizationSelections() {
    const { ctx } = this;

    const organizations = await ctx.model.Organization.findAll({
      attributes: ['id', 'uuid', 'name'],
    });

    ctx.body = new Result({ organizations }, MsgEnum.LOGIN_SUCCESS);
  }

  public async getTalentSelections() {
    const { ctx } = this;

    const talents = await ctx.model.Talent.findAll({
      attributes: ['id', 'uuid', 'name'],
    });

    ctx.body = new Result({ talents }, MsgEnum.LOGIN_SUCCESS);
  }

  async touristLogin() {
    const { ctx, app } = this;
    const errors = app.validator.validate(
      {
        name: { require, type: 'string', convertType: 'string' },
      },
      ctx.params,
    );
    if(errors) {
      ctx.status = 400;
    } else {
      const { name } = ctx.params;
      const uuid = uuidv4();
      if(name === 'tourist') {
        const params = { name, uuid };
        const token = await this.createToken(params);
        ctx.status = 200;
        ctx.body = new Result({
          name,
          token,
        });
      } else {
        ctx.status = 400;
      }
    }
  }
}
